<?php
namespace Controller;

use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Container;

class Admin extends Base
{
    public function __construct(Container $container)
    {

        parent::__construct($container);

        if ($this->getaccount() === false) {
            header('Location:/admin/login');
            exit;
        } else {
            $this->account = $this->getaccount();
            $this->view->assign('account', $this->account);
            $this->guard->generateToken();
            $this->assign = [
                'tk_name' => $this->guard->getTokenName(),
                'tk_value' => $this->guard->getTokenValue()
            ];
        }
    }

    public function index()
    {
        if($this->redis->exists('winning')){
            $winning=$this->redis->get('winning');//中奖概率
        }else{
            $winning=0;
        }

        if($this->redis->exists('min')){
            $min=$this->redis->get('min');//服装限量分发
        }else{
            $min=0;
        }
        if($this->redis->exists('max')){
            $max=$this->redis->get('max');//服装限量分发
        }else{
            $max=0;
        }

        $this->assign['winning']=$winning;
        $this->assign['min']=$min;
        $this->assign['max']=$max;

        $this->view->assign($this->assign);
        $this->view->display('admin/index.html');
    }

    public function user(Request $req, Response $res, $args)
    {
        $option = [];
        if (isset($args['data'])) {

            $dataarr = json_decode($this->decode_base64($args['data']), true);

            if (!isset($dataarr['page'])) {
                $page = 1;
            } else {
                $page = (int)$dataarr['page'];
            }
            if (isset($dataarr['search'])&&!empty($dataarr['search'])) {
                $search=$dataarr['search'];

               if($this->checkfrom->Mobile_check($search,array(1,2,3,4))===false){
                   $this->assign['search']=$this->unescape($search);
                   $option['username'] = array("'%".$this->unescape($search)."%'", 'like');
               }else{
                   $this->assign['search']=$search;
                   $option['mobile'] = array("'%$search%'", 'like');
               }

            }
            if (isset($dataarr['starttime'])&&!empty($dataarr['starttime'])) {
                $this->assign['starttime']=$dataarr['starttime'];
                $option['birthday'] = array(strtotime($dataarr['starttime']), '>=');
            }
            if (isset($dataarr['endtime'])&&!empty($dataarr['endtime'])) {
                $this->assign['endtime']=$dataarr['endtime'];
                $option['birthday'] = array(strtotime($dataarr['endtime']), '<=');
            }


        } else {
            $page = 1;

        }
        if(!empty($option)){
            $data = $this->db->where($option)->order(['regtime' => 'desc'])->limit($page, (int)$this->page['pagesize'])->select('tcp_user');
            $total = ceil($this->db->where($option)->count('tcp_user') / (int)$this->page['pagesize']);

        }else{
            $data = $this->db->order(['regtime' => 'desc'])->limit($page, (int)$this->page['pagesize'])->select('tcp_user');
            $total = ceil($this->db->count('tcp_user') / (int)$this->page['pagesize']);
        }

        if(empty($data)){
            $data=[];
            $total=0;
            $page=1;
        }
        $this->assign['data'] = $data;
        $this->assign['page'] = $page;
        $this->assign['total'] = $total;
        $this->view->assign($this->assign);
        $this->view->display('admin/user.html');
    }

    public function activity(Request $req, Response $res, $args)
    {
        $option = [];
        $option['is_delete']=array(0);
        if (isset($args['data'])) {

            $dataarr = json_decode($this->decode_base64($args['data']), true);
            if (!isset($dataarr['page'])) {
                $page = 1;
            } else {
                $page = (int)$dataarr['page'];
            }
            if (isset($dataarr['search'])&&!empty($dataarr['search'])) {
                $search=$dataarr['search'];
                $this->assign['search']=$this->unescape($search);
                $option['activityname'] = array("'%".$this->unescape($search)."%'", 'like');

            }
            if (isset($dataarr['minage'])&&!empty($dataarr['minage'])) {
                $this->assign['minage']=$dataarr['minage'];
                $option['minage'] = array($dataarr['minage'], '>=');
            }
            if (isset($dataarr['maxage'])&&!empty($dataarr['maxage'])) {
                $this->assign['maxage']=$dataarr['maxage'];
                $option['maxage'] = array($dataarr['maxage'], '<=');
            }
            if (isset($dataarr['starttime'])&&!empty($dataarr['starttime'])) {
                $this->assign['starttime']=$dataarr['starttime'];
                $option['starttime'] = array(strtotime($dataarr['starttime']), '>=');
            }
            if (isset($dataarr['endtime'])&&!empty($dataarr['endtime'])) {
                $this->assign['endtime']=$dataarr['endtime'];
                $option['endtime'] = array(strtotime($dataarr['endtime']), '<=');
            }

        } else {
            $page = 1;

        }
        $data = $this->db->where($option)->order(['createtime' => 'desc'])->limit($page, (int)$this->page['pagesize'])->select('tcp_activity');
        $total = ceil($this->db->where($option)->count('tcp_activity') / (int)$this->page['pagesize']);
        if(empty($data)){
            $data=[];
            $total=0;
            $page=1;
        }else{
          foreach ($data as $key=> $value){
              $where['act_id'] = array($value['id']);
              $data[$key]['joinnum']=$this->db->where($where)->count('tcp_user_activity');
          }
        }

        $this->assign['data'] = $data;
        $this->assign['page'] = $page;
        $this->assign['total'] = $total;
        $this->view->assign($this->assign);
        $this->view->display('admin/activity.html');
    }

    public function clothing(Request $req, Response $res, $args)
    {
        $option = [];
        $option['is_delete']=array(0);
        if (isset($args['data'])) {

            $dataarr = json_decode($this->decode_base64($args['data']), true);
            if (!isset($dataarr['page'])) {
                $page = 1;
            } else {
                $page = (int)$dataarr['page'];
            }
            if (isset($dataarr['search'])&&!empty($dataarr['search'])) {
                $search=$dataarr['search'];
                $this->assign['search']=$this->unescape($search);
                $option['clothing_name'] = array("'%".$this->unescape($search)."%'", 'like');

            }


        } else {
            $page = 1;

        }
        $data = $this->db->where($option)->order(['createtime' => 'desc'])->limit($page, (int)$this->page['pagesize'])->select('tcp_clothing');
        $total = ceil($this->db->where($option)->count('tcp_clothing') / (int)$this->page['pagesize']);
        if(empty($data)){
            $data=[];
            $total=0;
            $page=1;
        }else{
            foreach ($data as $key=> $value){
                $where['cid'] = array($value['id']);
                $data[$key]['joinnum']=$this->db->where($where)->count('tcp_user_clothing');
            }
        }

        $this->assign['data'] = $data;
        $this->assign['page'] = $page;
        $this->assign['total'] = $total;
        $this->view->assign($this->assign);
        $this->view->display('admin/clothing.html');
    }

    public function share(Request $req, Response $res, $args)
    {

        $where=' 1=1 ';
        $this->assign['state']=-1;
        if (isset($args['data'])) {

            $dataarr = json_decode($this->decode_base64($args['data']), true);
            if (!isset($dataarr['page'])) {
                $page = 1;
            } else {
                $page = (int)$dataarr['page'];
            }
            if (isset($dataarr['search'])&&!empty($dataarr['search'])) {
                $search=$dataarr['search'];

                if($this->checkfrom->Mobile_check($search,array(1,2,3,4))===false){
                    $this->assign['search']=$this->unescape($search);
                    $where.=" and username like  '%".$this->unescape($search)."%' ";

                }else{
                    $this->assign['search']=$search;
                    $where.=" mobile like  '%".$this->unescape($search)."%' ";

                }

            }
            if (isset($dataarr['state'])&&$dataarr['state']>=0) {
                $state=$dataarr['state'];
                $this->assign['state']=$state;
                $where.=" and  state =".$state;

            }


        } else {
            $page = 1;

        }
        $sqlstr=sprintf('SELECT `tcp_user`.`username`,`tcp_user`.`mobile`,`tcp_user_share`.* FROM `tcp_user_share` INNER JOIN `tcp_user` ON `tcp_user_share`.`uid`=`tcp_user`.uid  where %s  order by createtime desc limit %s,%s',$where,intval(($page-1)*(int)$this->page['pagesize']), (int)$this->page['pagesize']);
        $sqlcountstr=sprintf('SELECT count(tcp_user_share.id) as count FROM `tcp_user_share` INNER JOIN `tcp_user` ON `tcp_user_share`.`uid`=`tcp_user`.uid  where %s ',$where);
        $data = $this->db->doSql($sqlstr);
        $count = $this->db->doSql($sqlcountstr);
        $total = ceil($count[0]['count'] / (int)$this->page['pagesize']);

        if(empty($data)){
            $data=[];
            $total=0;
            $page=1;
        }

        $this->assign['data'] = $data;
        $this->assign['page'] = $page;
        $this->assign['total'] = $total;
        $this->view->assign($this->assign);
        $this->view->display('admin/share.html');
    }


    public function createactivity(Request $req, Response $res, $args)
    {

        if (!empty($args['act_id'])) {
            $result = $this->db->where(['id' => $args['act_id']])->find('tcp_activity');
            if (!empty($result)) {

                $result['starttime'] = date('Y-m-d', $result['starttime']);
                $result['endtime'] = date('Y-m-d', $result['endtime']);
                $this->assign = array_merge($result, $this->assign);

            } else {
                return $res->withRedirect('/admin/createactivity');
                exit;
            }
        }
        $this->view->assign($this->assign);
        $this->view->display('admin/createactivity.html');
    }
    public function createclothing(Request $req, Response $res, $args)
    {

        if (!empty($args['cid'])) {
            $result = $this->db->where(['id' => $args['cid']])->find('tcp_clothing');
            if (!empty($result)) {
                $result['color'][]= $this->db->where(['cid' => $args['cid']])->find('tcp_clothing_color');
                $result['size'][]= $this->db->where(['cid' => $args['cid']])->find('tcp_clothing_size');
                $this->assign = array_merge($result, $this->assign);

            } else {
                return $res->withRedirect('/admin/createclothing');
                exit;
            }
        }else{
            $result['color']= [];
            $result['size']= [];
            $this->assign = array_merge($result, $this->assign);
        }

        $this->view->assign($this->assign);
        $this->view->display('admin/createclothing.html');
    }
    public  function downactivity(Request $req, Response $res, $args){
        $id=(int)$args['act_id'];
        $activity=$this->db->where(['id'=>$id])->find('tcp_activity');

        $sqlstr=sprintf('SELECT tcp_user_activity.uid,username,mobile,tcp_user_activity.`createtime` FROM `tcp_user_activity` INNER JOIN `tcp_user` ON tcp_user_activity.`uid` = tcp_user.`uid` WHERE tcp_user_activity.`act_id`=%s',$id);
        $user_activity=$this->db->doSql($sqlstr);
        $objPHPExcel = new \PHPExcel();
        $filename=$activity['activityname'].date('Ymd').'.xls';
// 输出Excel表格到浏览器下载
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle($activity['activityname']);

        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,1,'活动名称');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,1,$activity['activityname']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,2,'姓名');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,2,'手机号');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(2,2,'宝宝详情');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(3,2,'报名时间');
        $rowindex=3;
        foreach ($user_activity as $value){


            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,$rowindex,$value['username']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,$rowindex,$value['mobile']);

            $Children=$this->getChildren($value['uid']);
            if(!empty($Children)){
                $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(2,$rowindex,$Children);
            }
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(3,$rowindex,date('Y-m-d',$value['createtime']));
            $rowindex++;
        }


        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save('php://output');
    }
    public  function downclothing(Request $req, Response $res, $args){
        $id=(int)$args['cid'];
        $clothing=$this->db->where(['id'=>$id])->find('tcp_clothing');

        $sqlstr=sprintf('SELECT tcp_user_clothing.uid,username,mobile,tcp_user_clothing.`createtime`,colorid,sizeid FROM `tcp_user_clothing` INNER JOIN `tcp_user` ON tcp_user_clothing.`uid` = tcp_user.`uid` WHERE tcp_user_clothing.`cid`=%s',$id);
        $user_clothing=$this->db->doSql($sqlstr);
        $objPHPExcel = new \PHPExcel();
        $filename=$clothing['clothing_name'].date('Ymd').'.xls';
// 输出Excel表格到浏览器下载
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle($clothing['clothing_name']);

        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,1,'服装名称');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,1,$clothing['clothing_name']);
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,2,'姓名');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,2,'手机号');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(2,2,'宝宝详情');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(3,2,'颜色');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(4,2,'尺寸');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(5,2,'兑换时间');
        $rowindex=3;
        foreach ($user_clothing as $value){


            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,$rowindex,$value['username']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,$rowindex,$value['mobile']);

            $Children=$this->getChildren($value['uid']);
            $colorobj=$this->getColor($value['colorid']);
            $sizeobj=$this->getSize($value['sizeid']);
            if(!empty($Children)){
                $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(2,$rowindex,$Children);
            }
            if(!empty($colorobj)){
                $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(3,$rowindex,$colorobj['colorname']);
            }
            if(!empty($sizeobj)){
                $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(4,$rowindex,$sizeobj['sizename']);
            }
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(5,$rowindex,date('Y-m-d',$value['createtime']));
            $rowindex++;
        }


        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save('php://output');
    }

    public  function downuser(Request $req, Response $res, $args){




        $objPHPExcel = new \PHPExcel();
        $filename='会员积分.xls';
// 输出Excel表格到浏览器下载
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("会员积分");
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,1,'姓名');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,1,'手机号');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(2,1,'生日');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(3,1,'性别');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(4,1,'地区');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(5,1,'积分');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(6,1,'注册日期');
        $rowindex=2;
        $user=$this->db->order(['regtime' => 'desc'])->select('tcp_user');
        foreach ($user as $value){


            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,$rowindex,$value['username']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,$rowindex,$value['mobile']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(2,$rowindex,date('Y-m-d',$value['birthday']));
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(3,$rowindex,$value['sex']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(4,$rowindex,$value['region'].'-'.$value['city'].'-'.$value['area']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(5,$rowindex,$value['intergtal']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(6,$rowindex,date('Y-m-d',$value['regtime']));
            $rowindex++;
        }


        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save('php://output');
    }

    public  function downshare(Request $req, Response $res, $args){
        $objPHPExcel = new \PHPExcel();
        $filename='分享上传.xls';
// 输出Excel表格到浏览器下载
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("分享上传");
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,1,'姓名');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,1,'手机号');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(2,1,'积分');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(3,1,'原因');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(4,1,'状态');
        $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(5,1,'上传日期');

        $rowindex=2;
        $sqlstr=sprintf('SELECT `tcp_user`.`username`,`tcp_user`.`mobile`,`tcp_user_share`.* FROM `tcp_user_share` INNER JOIN `tcp_user` ON `tcp_user_share`.`uid`=`tcp_user`.uid  order by createtime desc ');
        $data = $this->db->doSql($sqlstr);

        foreach ($data as $value){


            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(0,$rowindex,$value['username']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(1,$rowindex,$value['mobile']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(2,$rowindex,"+".$value['integral']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(3,$rowindex,$value['rank']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(4,$rowindex,$this->getStateTxt($value['state']));
            $objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow(5,$rowindex,date('Y-m-d',$value['createtime']));
            $rowindex++;
        }


        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save('php://output');
    }

    protected  function getChildren($uid){
        $user_children=$this->db->where(['uid'=> $uid])->select('tcp_user_children');
        if($user_children){
            $str='';
           foreach ($user_children as $val){
               $str.=$val['childrenname'].','.$val['sex'].','.date('Y-m-d',$val['birthday']).'|';
           }
           return  substr($str,0,strlen($str)-1);
        }else{
            return 0;
        }

    }
    protected  function getColor($colorid){
        $color=$this->db->where(['id'=> $colorid])->find('tcp_clothing_color');
        if($color){
            return  $color;
        }else{
            return 0;
        }

    }
    protected  function getSize($sizeid){
        $size=$this->db->where(['id'=> $sizeid])->find('tcp_clothing_size');
        if($size){
            return  $size;
        }else{
            return 0;
        }

    }
}